package com.example.authserver.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author : hongsw
 * @date : 2021-11-10-23:20
 */
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 先在内存中模拟出一个用户，后期需要关联数据库
     * 密码需要加密！！！！
     *
     * @param auth {@link org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder} 认证信息配置
     * @author hongsw
     * @date 2021/11/12 00:03
     **/
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("whsxt")
                .password(passwordEncoder().encode("whsxt"))
                .authorities("user:add");
    }

    /**
     * 因为我们用密码模式授权不需要登录，所以内部需要一个认证管理器，这边将AuthenticationManager通过@bean注解丢给Spring去管理
     *
     * @return {@link AuthenticationManager}
     * @author hongsw
     * @date 2021/11/11 23:05
     **/
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


    /**
     * 安全配置
     * csrf必须先关闭，不然post请求会有问题
     *
     * @param http {@link org.springframework.security.config.annotation.web.builders.HttpSecurity}
     * @author hongsw
     * @date 2021/11/12 00:06
     **/
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.formLogin()
                .and()
                .authorizeRequests()
                .anyRequest()
                .authenticated();
    }

    /**
     * 注入一个加密服务
     *
     * @return {@link PasswordEncoder}
     * @author hongsw
     * @date 2021/11/12 00:08
     **/
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}